package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import com.itheima.utils.AddressUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/***
 * 工作台-地址管理
 */


@RestController
@RequestMapping("/address")
public class AddressController {


    @Reference
    private AddressService addressService;


    //查询所有检查项
    @RequestMapping("/findAll")
    public Result findAll(){
        try{
            List<Address> list = addressService.findAll();//发送请求
            return new Result(true, MessageConstant.QUERY_ADDRESS_SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ADDRESS_FAIL);
        }
    }


    //根据id删除检查项
    @RequestMapping("/delete")
    //权限
    //@PreAuthorize("hasAuthority('ADDRESS_DELETE')")
    public Result delete(Integer id){
        try{
            Result result = addressService.delete(id);//发送请求
            return result;
        }catch (Exception e){
            String message = e.getMessage();
            e.printStackTrace();
            return new Result(false, message);
        }
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return addressService.findPage(queryPageBean);
    }


    //新增
    @RequestMapping("/add")
    public Result add(String addressName){
        try {
            String  str = new String(addressName.getBytes("ISO8859-1"), "utf-8");
            System.out.println(str);
            //创建地址对象
            Address address = new Address();
            address.setAddressName(str);//将地址设置未用户输入地址
            //将地址转换未经纬度
            Map<String, BigDecimal> map = AddressUtils.getLatAndLngByAddress(str);
            //获取经纬度
            BigDecimal lng = map.get("lng");
            BigDecimal lat = map.get("lat");
            //将经纬度加入address对象中
            address.setLng(lng.toString());
            address.setLat(lat.toString());
            addressService.add(address);//发送请求
            return new Result(true, MessageConstant.ADD_ADDRESS_SUCCESS);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_ADDRESS_FAIL);
        }




    }
}
